package cn.gson.crm.controller.position;

import cn.gson.crm.controller.BaseServlet;
import cn.gson.crm.model.dao.PositionDao;
import cn.gson.crm.model.entity.Position;


import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/position")
public class PositionServlet extends BaseServlet {
	
	private static final long serialVersionUID = 1L;
	private PositionDao postDao = new PositionDao();

	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String p = request.getParameter("page");
		String postStatus = request.getParameter("postStatus");
		List<Position> postList = postDao.getPostByStatus(Integer.parseInt((String)postStatus));
		request.setAttribute("postList", postList);
		
		if (p == null || p.isEmpty()) {
			p = "1";
		}
		Integer page = Integer.parseInt(p);
				
		if("1".equals(postStatus)){
			// 当前页数据
			List<Position> positionList = postDao.getPagePostListByType(Integer.parseInt((String)postStatus),page);
			// 总页数
			int totalPage = postDao.getTotalPage(Integer.parseInt((String)postStatus));

			request.setAttribute("queryString", noPageQueryString(request));
			request.setAttribute("positionList", positionList);
			request.setAttribute("totalPage", totalPage);
			request.setAttribute("page", page);
			
			forward("position/position_manage.jsp");
			return;
		}else{
			// 当前页数据
			List<Position> positionList = postDao.getPagePostListByType(Integer.parseInt((String)postStatus),page);
			// 总页数
			int totalPage = postDao.getTotalPage(Integer.parseInt((String)postStatus));
			request.setAttribute("queryString", noPageQueryString(request));
			request.setAttribute("positionList", positionList);
			request.setAttribute("totalPage", totalPage);
			request.setAttribute("page", page);
			
			forward("recycle_bin.jsp");
			return;
		}		
	}
	/**
	 * 
	 * @param request
	 * @return
	 */
	private String noPageQueryString(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();

		String paramsStr = "";
		int i = 0;
		for (String key : params.keySet()) {
			if ("page".equals(key)) {
				continue;
			}
			String[] valus = params.get(key);
			String query = "";
			for (int j = 0; j < valus.length; j++) {
				query += key + "=" + valus[j];
				if (j < valus.length - 1) {
					query += "&";
				}
			}
			paramsStr += query;
			if (i < params.keySet().size() - 1) {
				paramsStr += "&";
			}
			i++;
		}
		return paramsStr.isEmpty() ? "" : "&" + paramsStr;
	}
}
